package com.example.amqp.consumer.service;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Component
@RabbitListener(queues = "simpleQueue",concurrency = "1")
public class Receiving {


    private List<String> list = new ArrayList<>();

    private LocalDateTime receiveTime;


    @RabbitHandler
    public void receive(String msg) {

        receiveTime = LocalDateTime.now();
        list.add(msg);
        System.out.println("消息存入list,listSize-------: " + list.size());
        if (list.size() == 100){
            doReceive(list);
        }
    }

    @Scheduled(cron = "0/1 * * * * ?")
    private void overTimeTask(){
        if (receiveTime != null) {
            LocalDateTime now = LocalDateTime.now();
            Duration duration = Duration.between(receiveTime, now);
            long seconds = duration.getSeconds();
            System.out.println("当前时间："+now+"\n接收时间："+ receiveTime +"\n时间差:"+ seconds);
            if (seconds > 60L){
                doReceive(list);
                receiveTime = null;
            }

        }
    }

    private void doReceive(List<String> list){
        int i = 0;
        for (String s : list) {
            System.out.println("开始消费第"+i+"条消息");
            System.out.println("Received-------: " + s);
            i++;
            try {
                Thread.sleep(100L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        list.clear();
    }

}
